package mrpanyu.guitool.selectionreplace;

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.function.Function;

import mrpanyu.guitool.base.util.CommonUtils;
import mrpanyu.guitool.base.util.Log;

public class SelectionReplacer implements Runnable {

	private Function<String, String> handler;

	public SelectionReplacer(Function<String, String> handler) {
		this.handler = handler;
	}

	public void run() {
		try {
			Robot robot = new Robot();
			// Press Ctrl-C to copy selection to clipboard
			robot.keyPress(KeyEvent.VK_CONTROL);
			robot.keyPress(KeyEvent.VK_C);
			Thread.sleep(100);
			robot.keyRelease(KeyEvent.VK_CONTROL);
			robot.keyRelease(KeyEvent.VK_C);
			Thread.sleep(100);
			// Read and modify text
			String text = CommonUtils.getClipboardText();
			if (text != null) {
				String newText = handler.apply(text);
				if (newText != null) {
					CommonUtils.setClipboardText(newText);
					Thread.sleep(100);
					// Press Ctrl-V to paste
					robot.keyPress(KeyEvent.VK_CONTROL);
					robot.keyPress(KeyEvent.VK_V);
					Thread.sleep(100);
					robot.keyRelease(KeyEvent.VK_CONTROL);
					robot.keyRelease(KeyEvent.VK_V);
				}
			}
		} catch (Exception e) {
			Log.error("替换异常", e);
		}
	}

}
